package config

import (
	MSG "feishup2pclient/msg"
	"fmt"
	"os"
	"path"

	"github.com/spf13/viper"
)

const CfgDir = "./"

var PrvKey string

func init() {

	cfgPath := path.Join(CfgDir, "config.yaml")
	if _, err := os.Stat(cfgPath); err != nil {
		if _, err := os.Create(cfgPath); err != nil {
			println("test2")
			MSG.ErrCheck(fmt.Sprintf("%s", err))
			panic(err)
		}
	}
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(CfgDir)

	if err := viper.ReadInConfig(); err != nil {
		println("test1")
		MSG.ErrCheck(fmt.Sprintf("%s", err))
		panic(err)
	}

	PrvKey = viper.GetString("private_key")
	if viper.GetBool("log_able") {
		MSG.LogAble = true
	}

	viper.Set("log_able", MSG.LogAble)
	if err := viper.WriteConfig(); err != nil {
		println("test")
		panic(err)
	}
}

func WriteConfig(prvKey string) {
	viper.Set("private_key", prvKey)
	viper.Set("log_able", MSG.LogAble)
	if err := viper.WriteConfig(); err != nil {
		println("test")
		panic(err)
	}
}
